import { createRouter, createWebHashHistory } from 'vue-router'
import Login from '../components/Login.vue'

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/home',
    component: () => import('../components/home.vue'),
    redirect: '/welcome',
    children: [
      { path: '/welcome', component: () => import('../components/Welocme.vue') },
      { path: '/users', component: () => import('../components/users.vue') },
      { path: '/protects', component: () => import('../components/ProjectOne.vue') },
      { path: '/project/config', name: 'program-config', component: () => import('../components/comps/program-config/program-config.vue') },
      { path: '/project/detail', name: 'program-detail', component: () => import('../components/comps/program-detail/program-detail.vue') },
      { path: '/dicts', component: () => import('../components/Dictionary.vue') }
    ]
  }
]
const router = createRouter({
  history: createWebHashHistory(),
  routes
})
// router.beforeEach((to, from, next) => {
//   if (to.path !== '/login') next({ path: '/login' })
//   else next()
// })

router.beforeEach((to, from, next) => {
  // 如果访问的是首页，则放行
  if (to.path === '/login') {
    return next()
  }
  // 如果用户未登录，则跳转到/login
  const userInfo = JSON.parse(sessionStorage.getItem('userInfo'))
  if (!userInfo) {
    return next('/login')
  }
  // 如果用户已登陆，则放行
  next()
})

export default router
